# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import UserError, AccessError, ValidationError
from dateutil.relativedelta import relativedelta

class UpdateCost(models.TransientModel):
    _name = 'update.cost'

    year = fields.Float(string='年份')
    month = fields.Float(string='月份')
    chu_price = 0

    @api.multi
    def confirm(self):
        #采购入库的作业类型
        stock_picking_type_object_lists = self.env['stock.picking.type'].search([]).filtered(lambda m: m.code == 'incoming').mapped('id')
        #找出核算年月份的所有采购入库单
        stock_picking_objects = self.env['stock.picking'].search([]).filtered(lambda m: m.picking_type_id.id in stock_picking_type_object_lists\
                                                                              and m.receipts_date.year==self.year\
                                                                              and m.receipts_date.month==self.month\
                                                                              and m.state=='done')
        #销售出库单的作业类型
        stock_picking_type_out_lists = self.env['stock.picking.type'].search([]).filtered(lambda m: m.code == 'outgoing').mapped('id')
        # 找出核算年月份的所有销售出库单
        stock_picking_out_objects = self.env['stock.picking'].search([]).filtered(lambda m: m.picking_type_id.id in stock_picking_type_out_lists \
                      and m.receipts_date.year == self.year \
                      and m.receipts_date.month == self.month \
                      and m.state == 'done')
        #调拨的类型
        stock_picking_type_transfer_lists = self.env['stock.picking.type'].search([]).filtered(lambda m: m.code == 'internal' and m.name == '内部调拨' ).mapped('id')
        # 找出核算年月份的所有调拨单
        stock_picking_transfer_lists_objects = self.env['stock.picking'].search([]).filtered(lambda m: m.picking_type_id.id in stock_picking_type_transfer_lists \
                      and m.receipts_date.year == self.year \
                      and m.receipts_date.month == self.month \
                      and m.state == 'done')
        stock_picking_objects = self.order_set(stock_picking_objects + stock_picking_out_objects+stock_picking_transfer_lists_objects)
        cost_detail_objects = self.env['cost.detail.list'].search([])
        cost_detail_objects.unlink()
        for i in stock_picking_objects:
            #如果是内部调拨的话
            if i.picking_type_id.name == '内部调拨':
                #根据原库位找调出仓库
                out_warehouse_object = self.env['stock.warehouse'].search([('lot_stock_id','=',i.location_id.id)])
                #根据目的库位找调入仓库
                in_warehouse_object = self.env['stock.warehouse'].search([('lot_stock_id', '=', i.location_dest_id.id)])
                if out_warehouse_object and in_warehouse_object:
                    self.cost_detail_list_create(i, out_warehouse_object.id,'chu')
                    self.cost_detail_list_create(i, in_warehouse_object.id,'ru')
                continue
            self.cost_detail_list_create(i,i.picking_type_id.warehouse_id.id)
        #算出本月的成本核算结存数据
        cost_detail_objects = self.env['cost.detail.list'].search([])
        cost_objects_list=[]
        for i in cost_detail_objects:
            this_object = self.env['cost.detail.list'].search([('warehouse_id','=',i.warehouse_id.id),
                                                          ('product_id','=',i.product_id.id)], order='id desc', limit=1)
            cost_objects_list.append(this_object)

        cost_objects_list = list(set(cost_objects_list))
        for i in cost_objects_list:
            cost_computation_object = self.env['cost.computation'].create({'accounting_date':str(int(self.year))+str(int(self.month)).zfill(2),
                                                                           'warehouse_id':i.warehouse_id.id,
                                                                           'product_id':i.product_id.id,
                                                                           'count':i.jie_qty,
                                                                           'unit_price':i.jie_price,
                                                                           'total_price':i.jie_total
                                                                           })

    def order_set(self,stock_picking_objects):
        #给stock_pciking_objects排序
        new_stock_objects = stock_picking_objects.sorted(key=lambda r: r.receipts_date)
        return new_stock_objects


    def cost_detail_list_create(self,stock_picking_object,this_warehouse_id,type=False):
        for j in stock_picking_object.move_ids_without_package:
            qichu_qty = 0
            qichu_price = 0
            qichu_total = 0
            # 获取结存数据
            cost_detail_object = self.env['cost.detail.list'].search(
                [('warehouse_id', '=', this_warehouse_id),
                 ('product_id', '=', j.product_id.id),
                 ('year', '=', self.year),
                 ('month', '=', self.month)], order='id desc', limit=1)
            if not cost_detail_object:
                cost_computation_object = self.env['cost.computation'].search(
                    [('warehouse_id', '=', this_warehouse_id),
                     ('product_id', '=', j.product_id.id)], order='id desc', limit=1)
                if cost_computation_object:
                    qichu_qty = cost_computation_object.count
                    qichu_price = cost_computation_object.unit_price
                    qichu_total = cost_computation_object.total_price
            else:
                qichu_qty = cost_detail_object.jie_qty
                qichu_price = cost_detail_object.jie_price
                qichu_total = cost_detail_object.jie_total
            # 结存总金额
            if stock_picking_object.picking_type_id.code == 'incoming':
                # 本次结存数量
                this_qichun_qty = qichu_qty + j.quantity_done
                this_qichu_total = qichu_total + (j.quantity_done) * (j.purchase_line_id.price_subtotal / j.purchase_line_id.product_uom_qty)
                this_qichu_total = float("%.2f" % float(this_qichu_total))
                # 结存单价
                this_qichu_price = float("%.8f" % float(this_qichu_total / this_qichun_qty))
                # 存入收发存汇总表
                cost_detail_object = self.env['cost.detail.list'].create({'warehouse_id': this_warehouse_id,
                                                                          'product_id': j.product_id.id,
                                                                          'year': self.year,
                                                                          'month': self.month,
                                                                          'receipts_date': stock_picking_object.receipts_date,
                                                                          'qichu_qty': qichu_qty,
                                                                          'qichu_price': qichu_price,
                                                                          'qichu_total': qichu_total,
                                                                          'ru_qty': j.quantity_done,
                                                                          'ru_price': (j.purchase_line_id.price_subtotal / j.purchase_line_id.product_uom_qty),
                                                                          'ru_total': (j.quantity_done) * (j.purchase_line_id.price_subtotal / j.purchase_line_id.product_uom_qty),
                                                                          'jie_qty': this_qichun_qty,
                                                                          'jie_price': this_qichu_price,
                                                                          'jie_total': this_qichu_total
                                                                          })
            elif stock_picking_object.picking_type_id.code == 'outgoing':
                # 结存单价
                this_qichu_price = float("%.8f" % float(qichu_price))
                # 本次结存数量
                this_qichun_qty = qichu_qty - j.quantity_done
                this_qichu_total = this_qichun_qty*this_qichu_price
                this_qichu_total = float("%.2f" % float(this_qichu_total))
                # 存入收发存汇总表
                cost_detail_object = self.env['cost.detail.list'].create({'warehouse_id': this_warehouse_id,
                                                                          'product_id': j.product_id.id,
                                                                          'year': self.year,
                                                                          'month': self.month,
                                                                          'receipts_date': stock_picking_object.receipts_date,
                                                                          'qichu_qty': qichu_qty,
                                                                          'qichu_price': qichu_price,
                                                                          'qichu_total': qichu_total,
                                                                          'chu_qty': j.quantity_done,
                                                                          'chu_price': (j.sale_line_id.price_subtotal / j.sale_line_id.product_uom_qty),
                                                                          'chu_total': (j.quantity_done) * (j.sale_line_id.price_subtotal / j.sale_line_id.product_uom_qty),
                                                                          'jie_qty': this_qichun_qty,
                                                                          'jie_price': this_qichu_price,
                                                                          'jie_total': this_qichu_total
                                                                          })
            if type == 'chu':
                # 查询现在结存信息
                jiecun_uint_price = 0
                cost_detail_object = self.env['cost.detail.list'].search([('warehouse_id','=',this_warehouse_id),\
                                                                          ('product_id','=',j.product_id.id)],order ='id desc',limit=1)
                if not cost_detail_object:
                    cost_computation_object = self.env['cost.computation'].search(
                        [('warehouse_id', '=', this_warehouse_id),
                         ('product_id', '=', j.product_id.id)], order='id desc', limit=1)
                    if not cost_computation_object:
                        raise ValidationError(_("请维护:"+str(j.product_id.name)+str(j.product_id.default_code)+"的结存单价!核算调拨出库成本!"))
                    jiecun_uint_price = cost_computation_object.unit_price
                else:
                    jiecun_uint_price = cost_detail_object.jie_price
                self.chu_price  = jiecun_uint_price
                this_qichun_qty = qichu_qty - j.quantity_done
                this_qichu_total = qichu_total - (j.quantity_done) * (jiecun_uint_price)
                this_qichu_total = float("%.2f" % float(this_qichu_total))
                # 结存单价
                this_qichu_price = float("%.8f" % float(qichu_price))
                # 存入收发存汇总表
                cost_detail_object = self.env['cost.detail.list'].create({'warehouse_id': this_warehouse_id,
                                                                          'product_id': j.product_id.id,
                                                                          'year': self.year,
                                                                          'month': self.month,
                                                                          'receipts_date': stock_picking_object.receipts_date,
                                                                          'qichu_qty': qichu_qty,
                                                                          'qichu_price': qichu_price,
                                                                          'qichu_total': qichu_total,
                                                                          'chu_qty': j.quantity_done,
                                                                          'chu_price': jiecun_uint_price,
                                                                          'chu_total': (j.quantity_done) * (jiecun_uint_price),
                                                                          'jie_qty': this_qichun_qty,
                                                                          'jie_price': this_qichu_price,
                                                                          'jie_total': this_qichu_total
                                                                          })
            elif type == 'ru':
                # 查询现在结存信息
                jiecun_uint_price = self.chu_price
                this_qichun_qty = qichu_qty +j.quantity_done
                this_qichu_total = qichu_total + (j.quantity_done) * (jiecun_uint_price)
                this_qichu_total = float("%.2f" % float(this_qichu_total))
                # 结存单价
                this_qichu_price = float("%.8f" % float(this_qichu_total / this_qichun_qty))
                # 存入收发存汇总表
                cost_detail_object = self.env['cost.detail.list'].create({'warehouse_id': this_warehouse_id,
                                                                          'product_id': j.product_id.id,
                                                                          'year': self.year,
                                                                          'month': self.month,
                                                                          'receipts_date': stock_picking_object.receipts_date,
                                                                          'qichu_qty': qichu_qty,
                                                                          'qichu_price': qichu_price,
                                                                          'qichu_total': qichu_total,
                                                                          'ru_qty': j.quantity_done,
                                                                          'ru_price': jiecun_uint_price,
                                                                          'ru_total': (j.quantity_done) * (jiecun_uint_price),
                                                                          'jie_qty': this_qichun_qty,
                                                                          'jie_price': this_qichu_price,
                                                                          'jie_total': this_qichu_total
                                                                          })







